<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    //成绩信息
    var stus = {
      scores: [
        {
          name: '志远',
          score: 68
        },
        {
          name: '勇超',
          score: 72
        },
        {
          name: '嘉欣',
          score: 82
        },
        {
          name: '荣荣',
          score: 85
        },
        {
          name: '晓伟',
          score: 90
        },
      ]
    };

    //需求为 stus 添加一个属性 total, 每次都可以获得所有同学的总成绩
    //total 称为「计算属性」
    Object.defineProperty(stus, 'total', {
      get: function(){
        //计算总数 this 指向当前对象 stus
        //声明一个变量
        // var t = 0;
        // this.scores.forEach(function(item){
        //   t += item.score;
        // });
        // //返回
        // return t;

        //reduce
        return this.scores.reduce(function(prev, cur){
          return prev + cur.score;
        }, 0);
      }
    });

    console.log(stus.total);
    //增加学员的成绩
    stus.scores.push({
      name: '春雨',
      score: 99
    });

    console.log(stus.total);

  </script>
</body>
</html>